#include "app_mqtt.h"
#include "log/log.h"
#include "MQTTClient.h"
#include <string.h>

static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

static int (*recv_callback)(char *json) = NULL;


//消息发送完成的回调函数
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("消息发送完成");
}
 
//接收到消息（收到远程消息的回调函数）
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0;
    if(recv_callback)
    {
        result = recv_callback(message->payload)== 0? 1: 0;
    }
    printf("Message arrived\n");
    printf("     topic: %s\n", topicName);
    printf("   message: %.*s\n", message->payloadlen, (char*)message->payload);
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

//断开连接回调函数
void connlost(void *context, char *cause)
{
    log_error("mqtt conn lost: %s", cause);
}

//1.初始化mqtt
int app_mqtt_init(void)
{
    //初始化mqtt客户端
    if(MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        log_error("mqtt client create failed");
        return -1;
    }
    //注册接收消息的回调函数
    if(MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS)
    {
        log_error("mqtt client set callback failed");
        //销毁mqtt客户端
        MQTTClient_destroy(&client);
        return -1;
    }

    //连接mqtt服务器
    if(MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS)
    {
        log_error("mqtt client connect failed");
        //销毁mqtt客户端
        MQTTClient_destroy(&client);
        return -1;
    }

    //订阅主题
    if(MQTTClient_subscribe(client, TOPIC_R2G, QOS) != MQTTCLIENT_SUCCESS)
    {
        log_error("mqtt client subscribe failed");
        //销毁mqtt客户端
        app_mqtt_close();
        return -1;
    }
    log_debug("mqtt client init success");

    return 0;
}

//2.关闭mqtt客户端
void app_mqtt_close(void)
{
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

//3.发送消息给远程服务器
int app_mqtt_send(char *json)
{
    //指定要发送的数据
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json)+1;
    pubmsg.qos = QOS;

    if(MQTTClient_publishMessage(client, TOPIC_G2R, &pubmsg, NULL)!= MQTTCLIENT_SUCCESS);
    {
        log_error("mqtt client publish message failed");
        return -1;
    }
    log_debug("mqtt client publish message success,message:%s",json);
    return 0;
}

//4.注册接收处理远程消息的函数
void app_mqtt_registerRecvCallback(int (*callback)(char *json))
{
    recv_callback = callback;
}